
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.OrdersForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.4 $ $Date: 2008/11/10 12:45:19 $
 */

public final class MissedOrdersAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/missedOrders.do";

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        ArrayList missedList = new ArrayList ();
        OrdersForm subform  = ( OrdersForm ) form;
        String action       = request.getParameter ( "action" );
        String isSampleStr  = request.getParameter ( "isSample" );
        HashMap errors = new HashMap ();
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + "isSample="+request.getParameter("isSample"));
            return ( mapping.findForward ( "login" ) );
        }
        session.removeAttribute ( "ViewOrderRequest" );
        session.removeAttribute ( "SalesOrderHoldReleaseRequest" );

        if ( action == null )
        {
            request.setAttribute ( "showList", "FALSE" ); //Not to show the list by default
            subform.setByDate ( "ByRequestedDate" );
        }

        int isSample = 1; //default set to salesOrder
        if ( isSampleStr != null && isSampleStr.length () != 0 )
        {
            try
            {
                isSample = Integer.parseInt ( isSampleStr );
            }
            catch ( NumberFormatException ignore ) { isSample = 1; }
        }

        if ( "SearchOrder".equals ( action ) )
        {
            if ( user.isActionAllowed ( Functionality.SALES_MISSED_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            try
            {
                String customerId = ( String ) BeanUtils.getSimpleProperty ( form, "customerId" );
                String manufacturingPartNo = request.getParameter ( "manufacturingPartNo" );

                String fromDate = ( String ) BeanUtils.getSimpleProperty ( form, "fromDate" );
                String toDate = ( String ) BeanUtils.getSimpleProperty ( form, "toDate" );
                String salesOrderId = ( String ) BeanUtils.getSimpleProperty ( form, "salesOrderId" );
                String byDate = ( String ) request.getParameter ( "byDate" );
                String customerPO = ( String ) BeanUtils.getSimpleProperty ( form, "customerPO" );

                int year = 0;
                String bookingYear = request.getParameter ( "year" );
                if ( ( bookingYear != null ) && ( bookingYear.trim ().length () != 0 ) )
                {
                    try
                    {
                        year = Integer.parseInt ( bookingYear );
                    }
                    catch ( NumberFormatException nfe )
                    {
                        year = 0;
                    }
                }

                missedList = SalesDAO.loadMissedOrdersWithAll ( salesOrderId, customerId, manufacturingPartNo, isSample, byDate, year, customerPO );

                if ( missedList.size () == 0 )
                {
                    if ( SalesDAO.getSalesOrdersCount ( salesOrderId, customerId, manufacturingPartNo, isSample ) == 1 )
                    {
                        errors.put ( ERROR_MISSED_SALES_ORDER_NOT_FOUND, null );
                    }
                    else
                    {
                        if ( subform.getByDate ().equals ( "ByRequestedDate" ) )
                            errors.put ( ERROR_MISSED__REQUESTED_DATE_SALES_ORDER_NOT_FOUND, null );
                        else
                            errors.put ( ERROR_MISSED_SCHEDULED_DATE_SALES_ORDER_NOT_FOUND, null );
                    }
                }
                else
                {
                    request.setAttribute ( "showList", "TRUE" );
                }
            }
            catch ( Exception ex )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_MISSED_ORDERS );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not load Missed Orders." );
                session.setAttribute ( SessionKeys.ERROR_REPORT, ex );
            }


        }
        if ( "MissedOrdersList".equals ( action ) )
        {
            subform.setManufacturingPartNo ( "" );
            subform.setSalesOrderId ( ( "" ) );
            subform.setCustomerId ( 0 );
            request.setAttribute ( "showList", "FALSE" );
            subform.setByDate ( "ByRequestedDate" );
        }
        try
        {
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNames (isSample) );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "MissedOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "MissedOrders"));
        }
        catch (Exception ex)
        {
            errors.put("Error while Missed Sales Order data Loading ", null);
        }

        request.setAttribute ( "missedList", missedList );

        if ( !errors.isEmpty () )
        {
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        }
        return ( mapping.findForward ( "success" ) );

    }

    public static ArrayList loadManufacturingProducts( int isSample ) throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list   = null;
        if( isSample == 0 )
        {
            list = FinishedGoodsDAO.loadFinishedGoods().iterator ();
        }
        else
        {
            list = FinishedGoodsDAO.loadAllFinishedGoods().iterator ();
        }
        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            //It is better to replace with product Id here, instead of again searching the database with marketingpart no for productid
            //But i am leaving the other code as it is because we need to change lot of the code in the salesDAO. ;)
            parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getManufacturingPartNo () ) );
        }

        return parts;
    }
}
